package com.bw.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.utils.DateFormatUtil;
import com.bw.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.util.Collector;

public class DwdTrafficUniqueVisitorDetail {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        // TODO 2. 状态后端设置

        // TODO 3. 从 kafka dwd_traffic_page_log 主题读取日志数据，封装

        String topic = "dwd_traffic_page_log";

        String groupId = "dwd_traffic_user_jump_detail";

        FlinkKafkaConsumer<String> flinkKafkaConsumer = MyKafkaUtil.getFlinkKafkaConsumer(topic, groupId);

        DataStreamSource<String> pageLog = env.addSource(flinkKafkaConsumer);

//        pageLog.print();


        // TODO 4. 转换结构
        SingleOutputStreamOperator<JSONObject> mappedStream = pageLog.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    JSONObject jsonOb = JSON.parseObject(s);
                    collector.collect(jsonOb);
                }catch (Exception e){
                    System.out.println("脏数据："+s);
                }
            }
        });

        // TODO 5. 过滤 last_page_id 不为 null 的数据

        SingleOutputStreamOperator<JSONObject> firstPageStream = mappedStream.filter(jsonOb -> jsonOb.getJSONObject("page").getString("last_page_id") == null);

        // TODO 6. 按照 mid 分组
        KeyedStream<JSONObject, String> keyedStream = firstPageStream.keyBy(o -> o.getJSONObject("common").getString("mid"));

        // TODO 7. 通过 Flink 状态编程过滤独立访客记录

        SingleOutputStreamOperator<JSONObject> filterStream = keyedStream.filter(new RichFilterFunction<JSONObject>() {

            private ValueState<String> lastVisitDt;


            public void open(Configuration paramenters) throws Exception {
                super.open(paramenters);
                ValueStateDescriptor<String> valueStateDescriptor =
                        new ValueStateDescriptor<>("last_visit_dt", String.class);
                //5.1  8:8:8     5.2  7点     5.2 8:8:8
                //配置状态的生命周期
                valueStateDescriptor.enableTimeToLive(
                        StateTtlConfig
                                .newBuilder(Time.days(1L))// 过期时间1天
                                //在跟新状态的时候也要跟新存活时间
                                // 设置在创建和更新状态时更新存活时间
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                .build()
                );
                this.lastVisitDt = getRuntimeContext().getState(valueStateDescriptor);
            }


            @Override
            public boolean filter(JSONObject jsonObject) throws Exception {

                String visitDt = DateFormatUtil.toDate(jsonObject.getLong("ts"));

                String lastDt = lastVisitDt.value();

                if (lastDt == null || lastDt.equals(visitDt)) {
                    lastVisitDt.update(visitDt);
                    return true;
                }

                return false;
            }
        });

        // TODO 8. 将独立访客数据写入
        // Kafka dwd_traffic_unique_visitor_detail 主题

        String targetTopic = "dwd_traffic_unique_visitor_detail";

        filterStream.print(">>>>>>>>");


        FlinkKafkaProducer<String> kafkaProducer = MyKafkaUtil.getFlinkKafkaProducer(targetTopic);

        filterStream.map(a->a.toJSONString()).addSink(kafkaProducer);


        env.execute();


    }
}
